package com.cndongtai.controller.upload;

import java.text.SimpleDateFormat;

import javax.annotation.Resource;

import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.cndongtai.controller.BaseController;
import com.cndongtai.po.UploadFile;
import com.cndongtai.service.upload.UploadService;
import com.cndongtai.util.ValidateUtil;

@Controller
public class FileUploadController extends BaseController{
	@Resource(name = "uploadService")
	private UploadService uploadService;

	private static final long FILE_MAX_SIZE = 1024 * 1024 * 6;
	
	@ResponseBody
	@RequestMapping("/uploadFile")
	public void uploadFile(MultipartFile file) {
		JSONObject result = new JSONObject();
		if(null!=file && file.getSize()>0) {
			// 校验扩展名
			if (null == file
					|| !ValidateUtil.checkFirmwareFileExt(file.getOriginalFilename())) {
				result.put("success", "-1");
				result.put("msg", "文件格式错误！");
				this.writeData(result);
				return;
			}

			// 判断文件大小
			if (file.getSize() > FILE_MAX_SIZE) {
				result.put("success", "-1");
				result.put("msg", "文件大小不得超过6M！");
				this.writeData(result);
				return;
			}

			UploadFile uploadFile;
			try {
				uploadFile = uploadService.uploadFile(request, file);
				if(null==uploadFile) {
					result.put("success", -1);
					result.put("msg", "文件上传失败！");
				}else {
					SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					result.put("success", 0);
					result.put("msg", "文件上传成功！");
					result.put("fileId", uploadFile.getId().toString());
					result.put("filePath", uploadFile.getFilePath());
					result.put("fileName", uploadFile.getFileName());
					result.put("uploadTime", sf.format(uploadFile.getUploadTime()));
				}
			} catch (Exception e) {
				log.error(e.getMessage());;
				result.put("success", -1);
				result.put("msg", "文件格式错误，上传失败！");
			}
		}else {
			result.put("success", -1);
			result.put("msg", "文件上传失败！");
		}

		this.writeData(result);
	}
	
}
